package com.viewhigh.wechat.sdk.bean;

import java.io.Serializable;
import java.util.Map;

import com.alibaba.fastjson.JSON;

/**
 * @intro 封装 access_token
 * @author lengyu
 * @since 2016年3月29日 下午4:32:28
 */
public class AccessTokenBean implements Serializable {
    private static final long serialVersionUID = 7692452118142653223L;
    private String accessToken; // 正确获取到 access_token 时有值
    private Integer expiresIn; // 正确获取到 access_token 时有值默认为7200秒
    //private Integer errcode; // 出错时有值
    //private String errmsg; // 出错时有值
    private Long expiredTime; // 正确获取到 access_token 时有值，存放过期时间

    //private String json;

    @SuppressWarnings("unchecked")
    public AccessTokenBean(String jsonStr) {
        //this.json = jsonStr;
        try {
            Map<String, Object> temp = JSON.parseObject(jsonStr, Map.class);
            accessToken = (String) temp.get("access_token");
            expiresIn = getInt(temp, "expires_in");
            //errcode = getInt(temp, "errcode");
            //errmsg = (String) temp.get("errmsg");

            if (expiresIn != null) {
                expiredTime = System.currentTimeMillis() + ((expiresIn - 200) * 1000);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public String getAccessToken() {
        return accessToken;
    }


    public Integer getExpiresIn() {
        return expiresIn;
    }


    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }


    public void setExpiresIn(Integer expiresIn) {
        this.expiresIn = expiresIn;
    }


   /* public Integer getErrcode() {
        return errcode;
    }

    public void setErrcode(Integer errcode) {
        this.errcode = errcode;
    }

    public String getErrmsg() {
        return errmsg;
    }

    public void setErrmsg(String errmsg) {
        this.errmsg = errmsg;
    }*/

    public Long getExpiredTime() {
        return expiredTime;
    }

    public void setExpiredTime(Long expiredTime) {
        this.expiredTime = expiredTime;
    }

    public static long getSerialversionuid() {
        return serialVersionUID;
    }

  /*  public String getJson() {
        return json;
    }

    public void setJson(String json) {
        this.json = json;
    }*/

    private Integer getInt(Map<String, Object> temp, String key) {
        Number number = (Number) temp.get(key);
        return number == null ? null : number.intValue();
    }

    /**
     * 校验是否可用
     * 
     * @return
     */
    public boolean isAvailable() {
        if (expiredTime == null)
            return false;
        /*if (errcode != null)
            return false;*/
        if (expiredTime < System.currentTimeMillis())
            return false;
        return accessToken != null;
    }

}